#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import datetime
import django.utils.simplejson
import re
import string
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from appengine.billmodel import BillCategory
from appengine.billmodel import Bill

class GetBillData(webapp.RequestHandler):
	def post(self):
		search_date = datetime.datetime.strptime(self.request.get("date"), "%Y-%m")
		if search_date.month == 12:
			bills = db.GqlQuery("SELECT * FROM Bill WHERE AccountName=:1 AND CreateTime>=:2 AND CreateTime<=:3 ORDER BY CreateTime ASC", self.request.get("user"), datetime.date(search_date.year, search_date.month, 1), (datetime.date(search_date.year + 1, 1, 1) - datetime.timedelta(1)))
		else:
			bills = db.GqlQuery("SELECT * FROM Bill WHERE AccountName=:1 AND CreateTime>=:2 AND CreateTime<=:3 ORDER BY CreateTime ASC", self.request.get("user"), datetime.date(search_date.year, search_date.month, 1), (datetime.date(search_date.year, search_date.month + 1, 1) - datetime.timedelta(1)))

		curbill_list = []
		bill_category = {}
		for bill in bills:
			if bill_category.has_key(bill.BillCategory):
				bill_category[bill.BillCategory] += bill.PayAmount
			else:
				bill_category[bill.BillCategory] = bill.PayAmount
			curbill_list.append([bill.key().id(), bill.PayAmount, bill.BillCategory, bill.Remark, bill.CreateTime.strftime("%Y-%m-%d")])

		chart2_data = []
		bill_category_keys = bill_category.keys()
		bill_category_keys.sort()
		for key in bill_category_keys:
			chart2_data.append([key, ("%0.02f" % bill_category[key])])
		self.response.out.write("({ErrCode:0, ErrMsg:'', BillData:"+django.utils.simplejson.dumps(curbill_list)+", ChartXml:"+django.utils.simplejson.dumps(chart2_data)+"})")

application = webapp.WSGIApplication([('/interface/getbilldata.php', GetBillData)], debug=True)

def main():
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
	main()

